package com.tnovoselec.android.mojevijesti.activity;

import android.content.Intent;
import android.os.Bundle;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.widget.ShareActionProvider;
import com.tnovoselec.android.mojevijesti.R;
import com.tnovoselec.android.mojevijesti.dto.NewsResultHolder;
import com.tnovoselec.android.mojevijesti.fragment.NewsDetailsFragment;
import com.tnovoselec.android.mojevijesti.fragment.NewsDetailsFragment.NewsItemChangedListener;

public class NewsDetailsActivity extends SherlockFragmentActivity implements NewsItemChangedListener {

	private ShareActionProvider mShareActionProvider;
	int channel;
	int position;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		try {
			channel = getIntent().getIntExtra("channel", 0);
			position = getIntent().getIntExtra("position", 0);
			NewsDetailsFragment ndf = new NewsDetailsFragment();
			Bundle args = new Bundle();
			args.putInt("channel", channel);
			args.putInt("position", position);
			ndf.setArguments(args);
			ndf.setListener(this);
			getSupportFragmentManager().beginTransaction().add(android.R.id.content, ndf).commit();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	@Override
	protected void onStart() {
		super.onStart();
		ActionBar bar = getSupportActionBar();
		if (bar != null) {
			bar.setDisplayHomeAsUpEnabled(true);
		}
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate menu resource file.
		getSupportMenuInflater().inflate(R.menu.news_details_menu, menu);

		// Locate MenuItem with ShareActionProvider
		MenuItem actionItem = menu.findItem(R.id.menu_item_share_action_provider_action_bar);

		// Fetch and store ShareActionProvider
		mShareActionProvider = (ShareActionProvider) actionItem.getActionProvider();

		setShareIntent(createShareIntent(position));
		return true;
	}

	private void setShareIntent(Intent shareIntent) {
		if (mShareActionProvider != null) {
			mShareActionProvider.setShareIntent(shareIntent);
		}
	}

	@Override
	public void onNewsItemChanged(int position) {
		setShareIntent(createShareIntent(position));

	}

	private Intent createShareIntent(int position) {
		Intent shareIntent = new Intent(Intent.ACTION_SEND);
		shareIntent.setType("text/*");
		shareIntent.putExtra(Intent.EXTRA_TEXT, NewsResultHolder.get(channel).get(position).getLink());
		return shareIntent;
	}
}
